import React, { Component } from 'react';
import { observer } from 'mobx-react';
import ApiHelper from '@/store/ApiHelper';
import MModal from '@/component/common/MModal';

@observer class FilterListPage extends Component {
    constructor(props) {
        super(props);
        this._defaultState = {};
    }
    state = {
        loading: true,
        spinning: false,
        dataList: [],
        result_info: {},
        current_page: 1,
        per_page: 10,
        total: 0,
        query: {}
    };
    //必须用在constructor中
    _setDefaultState(state) {
        this._defaultState = {
            ...state
        };
        this.state = {
            ...this._defaultState, ...this.state
        }
    }
    listApiType = '';
    defaultQuery = {};
    async componentDidMount() {
        this._isMounted = true;
        if (typeof this.pageBeforeMount === 'function') await this.pageBeforeMount();
        await this.getDataList();
        if (typeof this.pageDidMount === 'function') await this.pageDidMount();
    }
    componentWillUnmount() {
        this._isMounted = false;
    }
    pageOnChange = async pageNumber => {
        const query = this.state.query;
        await this.getDataList(pageNumber, query);
    };
    refresh = async () => {
        const { current_page, query } = this.state;
        await this.getDataList(current_page, query);
    };
    getDataList = async (current_page = 1, query = {}) => {
        //获取列表
        if (this.listApiType == '' || this.state.spinning) return;
        this.setState({ current_page, query, spinning: true });
        const data = { per_page: 10, current_page, ...this.defaultQuery, ...query };
        const result = await ApiHelper.requestPost(this.listApiType, data);
        if (!result.status) {
            this._setState({ spinning: false });
            return MModal.success({ title: '错误提示', content: result.info });
        }
        const info = result.info;
        this._setState({
            dataList: info.data,
            per_page: info.per_page,
            current_page: info.current_page,
            total: info.total,
            result_info: info,
            spinning: false
        });
    };
    getDataListWithFilter = async query => {
        await this.getDataList(1, query);
    };
    //fix异步
    _setState = state => {
        if (this._isMounted) this.setState(state);
    };
}

export default FilterListPage;